package models

import (
	"strconv"

	"github.com/astaxie/beego"

	"github.com/astaxie/beego/orm"
)

const (
	RoleRsvd     = 0 // 保留
	RoleAdmin    = 1 // 管理员
	RoleManager  = 2 // 项目经理
	RoleUser     = 3 // 普通用户
	RoleCustomer = 4 // 需求用户
)

const (
	UserStatusReserved = 0
	UserStatusActive   = 1
	UserStatusInActive = 2
)

type User struct {
	Id           int64  `orm:"column(id)"`
	Username     string `orm:"unique"`
	Password     string `orm:"size(32)"`
	Email        string `orm:"unique"`
	Phone        string `orm:"unique"`
	Status       uint8
	Role         uint8
	Avatar       string
	Updated      int64
	RegisterTime int64
	RegisterIP   string `orm:"column(register_ip)"`
	LoginTime    int64
	LoginIP      string `orm:"column(login_ip)"`
}

func (u *User) TableName() string {
	return "fh_user"
}

func (u *User) String() string {
	return strconv.FormatInt(u.Id, 10)
}

func (u *User) Insert() error {
	if _, err := orm.NewOrm().Insert(u); err != nil {
		return err
	}
	return nil
}

func (u *User) Read(fields ...string) error {
	err := orm.NewOrm().Read(u, fields...)
	if err != nil {
		return err
	}
	return nil
}

func (u *User) Update(fields ...string) error {
	_, err := orm.NewOrm().Update(u, fields...)
	if err != nil {
		return err
	}
	return nil
}

func (u *User) Delete() error {
	_, err := orm.NewOrm().Delete(u)
	if err != nil {
		return err
	}
	return nil
}

func init() {
	orm.RegisterModel(new(User))
}

func CreateUser(username, password string) error {
	u := User{Username: username, Password: password, Status: 1}
	err := u.Insert()
	if err != nil {
		beego.Error(err.Error())
	}
	return err
}

func QueryUserByUsername(username string) ([]User, error) {
	query := orm.NewOrm().QueryTable("fh_user")
	users := make([]User, 0)
	_, err := query.Filter("username__icontains", username).Limit(-1).All(&users)
	if err != nil {
		beego.Error(err.Error())
	}
	return users, err
}

func UpdateUserPassword(username, password string) error {
	u := User{Username: username, Password: password}
	err := u.Read("username")
	if err != nil {
		beego.Error(err.Error())
		return err
	}
	err = u.Update("password")
	if err != nil {
		beego.Error(err.Error())
		return err
	}
	return nil
}
